package com.jiajia.study.nio.chapter01;

import java.nio.ByteBuffer;

public class TestNio04 {
    public static void main(String[] args) {
//        test1();
//        test2();
//        test3();
//        test4();
        test5();


    }
    private static void test5() {
        // 创建 byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[]{'a','b','c','d'});

        // 切换成读模式
        byteBuffer.flip();

        // 从 bytebuffer 中读数据
        System.out.println(byteBuffer.get());
        System.out.println(byteBuffer.capacity() + ":" + byteBuffer.position() + ":" + byteBuffer.limit());
//        System.out.println(byteBuffer.get());
//        System.out.println(byteBuffer.capacity() + ":" + byteBuffer.position() + ":" + byteBuffer.limit());


        byteBuffer.compact();
        System.out.println(byteBuffer.capacity() + ":" + byteBuffer.position() + ":" + byteBuffer.limit());
        /**
         * Exception in thread "main" java.nio.BufferUnderflowException
         */
//        System.out.println(byteBuffer.get());
    }


    private static void test4() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[]{'a','b','c','d'});
        System.out.println("position: " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " +byteBuffer.capacity());
        // 写模式  -> 切换成写模式
        byteBuffer.clear();
        System.out.println("position: " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " +byteBuffer.capacity());

    }

    private static void test3() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[]{'a','b','c','d'});
        System.out.println("position: " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " +byteBuffer.capacity());

        // 切换成读模式
        byteBuffer.flip();
        System.out.println("position: " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " +byteBuffer.capacity());


    }

    private static void test2() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[]{'a','b','c','d'});
        System.out.println("position : " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " + byteBuffer.capacity());
    }

    private static void test1() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        System.out.println(byteBuffer.capacity());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.position());
//        System.out.println(byteBuffer.mark());
    }


}
